﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections.ObjectModel;

namespace PulsePrototype.PulseManagers.Components
{
    public class ComponentCollection : KeyedCollection<String, BaseComponent>
    {
        /// <summary>
        /// Called when a Component is added to this collection.
        /// </summary>
        public event Action<BaseComponent> ComponentAdded;

        /// <summary>
        /// Called when a Component is removed from this collection.
        /// </summary>
        public event Action<BaseComponent> ComponentRemoved;

        private BaseEntity _Entity;

        public BaseEntity Entity
        {
            get { return _Entity; }
            set
            {
                if (_Entity != null)
                    throw new InvalidOperationException("Unable to change parent of entity after it has been set.");
                _Entity = value;
            }
        }

        /// Gets the first component that is, or derives from, the given type.
        /// If no component is found with the given type, returns null.
        /// </summary>
        /// <param name="t">The type of the component to get.</param>
        public BaseComponent this[Type t]
        {
            get
            {
                foreach (var Component in this)
                {
                    var CompType = Component.GetType();
                    if (CompType == t || CompType.IsSubclassOf(t))
                        return Component;
                }
                return null;
            }
        }

        /// <summary>
        /// Used only for Serialization.
        /// </summary>
        public ComponentCollection() { }

        /// <summary>
        /// Creates a new ComponentCollection for the given Entity.
        /// </summary>
        public ComponentCollection(BaseEntity entity)
        {
            this._Entity = entity;
        }

        // <summary>
        /// Returns the name of this Component as a key.
        /// </summary>
        protected override string GetKeyForItem(BaseComponent item)
        {
            return item.Name;
        }
    }
}
